import { useEffect, useState } from "react";
import { Button, Dropdown, Menu, message, Modal, Row } from "antd";
import type { MenuProps } from 'antd';
import { DownOutlined } from "@ant-design/icons";

import "./CueWordManage.css"
import { deleteAxios, get, post, putAxios } from "@/service/axiosManager";

export default function CueWordManage({ open, setOpen }: { open: boolean, setOpen: (open: boolean) => void }) {
    const [cueWordDatas, setCueWordDatas] = useState<any[]>();
    const [cueWordEdit, setCueWordEdit] = useState<boolean>(false);
    const [cueWordAdd, setCueWordAdd] = useState<boolean>(false);

    useEffect(() => {
        if (open) {
            loadWordTips();
        }
    }, [open]);


    const loadWordTips = () => {
        // get("/cue/word/all").then((res: any) => {
        get("/cue/word/owner/all").then((res: any) => {
            console.log('加载提示词成功', res);
            const wordTips = res.result.map((item: any) => {
                return {
                    id: item.id,
                    word: item.words,
                    title: item.title,
                    command: item.command,
                    onClick: (e: any, item: any) => {
                        console.log('点击', e);
                        if (item.key) {
                            console.log("send: " + item.key);

                        }
                    },
                }
            })

            setCueWordDatas(wordTips);
        }).catch((err: any) => {
            console.log('加载提示词失败', err);
        });
    }

    const closeEdit = () => {
        loadWordTips();
        setCueWordEdit(false);
    };

    const confirmEdit = (item: any, changeItem: any) => {
        if (!(changeItem.title || changeItem.word || changeItem.command)) {
            console.log("item: 无修改");
            closeEdit();
            return;
        }
        console.log("item: " + JSON.stringify(changeItem));
        item.title = changeItem.title;
        item.words = changeItem.word;
        item.command = changeItem.command;
        putAxios("/cue/word", item).then((res: any) => {
            console.log('修改提示词成功', res);
            closeEdit();
        }).catch((err: any) => {
            console.log('修改提示词失败', err);
        });
    };
    const deleteItem = (paramItem: any) => {
        Modal.confirm({
            title: '确定删除提示词吗？',
            onOk: () => {
                console.log("deleteItem: " + JSON.stringify(paramItem));
                deleteAxios("/cue/word/" + paramItem.id).then((res: any) => {
                    console.log('删除提示词成功', res);
                    loadWordTips();
                }).catch((err: any) => {
                    console.log('删除提示词失败', err);
                });
            }
        });
    };

    const addItemConfirm = (item: any) => {
        console.log("addItemConfirm: " + JSON.stringify(item));
        const pcueTitle = item.title
        const pcueWords = item.word
        const pcueCommand = item.command
        const cueWord = {
            "title": pcueTitle,
            "words": pcueWords,
            "command": pcueCommand,
        };
        post("/cue/word", cueWord).then((res) => {
            console.log(res);
            let msg = res?.result;
            if (res.code !== 0 || !res.success || !msg) {
                msg = res?.message || "添加失败";
                message.error(msg);
            }
            message.info("添加成功");
            closeEdit();
            setCueWordAdd(false);
        }).catch((err) => {
            console.log(err);
            message.error(err);
        })
    };

    const editRow = (editItem: any) => {
        if (cueWordEdit) {
            message.warning("无法同时编辑多行");
            return;
        }
        btnEdit(editItem, true);
    };

    const btnEdit = (editItem: any, isEdit: boolean) => {
        editItem.isEdit = isEdit;
        setCueWordEdit(editItem.isEdit);
        const tmpDatas = cueWordDatas?.map((item, index) => {
            return item.id === editItem.id ? editItem : item;
        });
        setCueWordDatas(tmpDatas);
    };
    let insertItem: { title?: any, word?: any, command?: any } = {};
    return (
        <>
            <Modal title="维护提示词" centered destroyOnClose open={open} footer={null} width={800} onCancel={() => { setOpen(false); }} afterClose={() => closeEdit()}>
                <div className="data_header">
                    <Row justify="end">
                        <Button color="primary" variant="outlined" onClick={() => { setCueWordAdd(true) }}>
                            新增
                        </Button>
                    </Row>

                </div>
                <div className="data_title">
                    <div className="cue_title data_col">标题</div>
                    <div className="cue_word data_col">提示词</div>
                    <div className="cue_desc data_col">命令</div>
                    <div className="cue_option option_col">操作</div>
                </div>
                <div className="data_content">
                    {cueWordAdd && <div className="data_row" key={"row_-1"}>
                        <div className="data_col">
                            <input className="data_col_input" onChange={(e) => { insertItem.title = e.target.value }}></input>
                        </div>
                        <div className="data_col">
                            <input className="data_col_input" onChange={(e) => { insertItem.word = e.target.value }}></input>
                        </div>
                        <div className="data_col">
                            <input className="data_col_input" onChange={(e) => { insertItem.command = e.target.value }}></input>
                        </div>
                        <div className="row_option option_col">
                            <div className="open_btn" onClick={() => { setCueWordAdd(false) }}>取消</div>
                            <div className="open_btn" onClick={() => { addItemConfirm(insertItem) }}>确认</div>
                        </div>
                    </div>}
                    {cueWordDatas && cueWordDatas.map((item, index) => {
                        let changeItem: { title?: any, word?: any, command?: any } = {};
                        if (item.isEdit) {
                            return (
                                <div className="data_row" key={"row_" + index}>
                                    <div className="data_col">
                                        <input className="data_col_input" defaultValue={item.title} onChange={(e) => { changeItem.title = e.target.value }}></input>
                                    </div>
                                    <div className="data_col">
                                        <input className="data_col_input" defaultValue={item.word} onChange={(e) => { changeItem.word = e.target.value }}></input>
                                    </div>
                                    <div className="data_col">
                                        <input className="data_col_input" defaultValue={item.command} onChange={(e) => { changeItem.command = e.target.value }}></input>
                                    </div>
                                    <div className="row_option option_col">
                                        <div className="open_btn" onClick={() => { btnEdit(item, false); }}>取消</div>
                                        <div className="open_btn" onClick={() => { confirmEdit(item, changeItem) }}>确认</div>
                                    </div>
                                </div>
                            )
                        } else {
                            const items: MenuProps["items"] = [{
                                key: index + '-' + '1',
                                label: (
                                    <div onClick={() => { deleteItem(item) }}>
                                        删除
                                    </div>
                                ),
                            }];
                            return (
                                <div className="data_row" key={"row_" + index}>
                                    <div className="data_col">{item.title}</div>
                                    <div className="data_col">{item.word}</div>
                                    <div className="data_col">{item.command}</div>
                                    <div className="row_option option_col">
                                        <div className="open_btn" onClick={() => { editRow(item) }}>编辑</div>
                                        <div className="open_btn" style={{ color: "#ff4d4f" }} onClick={() => { deleteItem(item) }}>删除</div>
                                        {/* <Dropdown menu={{ items }}>
                                            <div className="more_btn open_btn" onClick={(e) => e.preventDefault()}>
                                                更多
                                                <DownOutlined style={{ width: 12, height: 12 }} />
                                            </div>
                                        </Dropdown> */}
                                    </div>
                                </div>
                            )
                        }
                    })}
                </div>

            </Modal>
        </>
    );
}